﻿using Furion;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Events;
using System;
using System.Text;
using YFurion.Extensions;

namespace Microsoft.Extensions.Hosting
{
    public static class SerilogHostingExtensions
    {
        public static IHostBuilder UseYFurionSerilogDefault(this IHostBuilder builder, Action<LoggerConfiguration> configAction = null)
        {
            if (configAction != null)
            {
                return builder.UseSerilogDefault(configAction);
            }

            return builder.UseSerilogDefault(configAction =>
            {
                string date = DateTime.Now.ToString("yyyyMMdd");
                IConfiguration configuration = App.Configuration;
                IConfigurationSection configurationSection = configuration.GetSection("Serilog");
                string outputTemplate = configurationSection.GetValue<string>("OutputTemplate");
                if (outputTemplate.IsNullOrWhiteSpace())
                {
                    outputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}";
                }
                outputTemplate += new string('-', 100);
                bool rollOnFileSizeLimit = configurationSection.GetValue<bool>("RollOnFileSizeLimit");
                bool isOutputConsole = configurationSection.GetValue<bool>("IsOutputConsole");
                configAction.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level != LogEventLevel.Error).WriteTo.File($"Logs/{date}/.log", rollingInterval: RollingInterval.Day, outputTemplate: outputTemplate, rollOnFileSizeLimit: rollOnFileSizeLimit, encoding: Encoding.UTF8));
                configAction.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Error).WriteTo.File($"Logs/{date}/{LogEventLevel.Error}.log", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, encoding: Encoding.UTF8));
                if (isOutputConsole)
                {
                    configAction.WriteTo.Console(outputTemplate: outputTemplate);
                }
            });

        }
    }
}
